package assignment1;

import classdemo.ThreadServerTest;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;

/**
 * @DESCRIPATION 服务器端计算平均值结果再传给客户端
 * @AUTHOR 戴超
 * @DATE 2018/6/19
 **/
public class GradeServer extends Thread {
    public Socket socket;
    public static CountDownLatch countDownLatch = new CountDownLatch(10);
    static volatile int count = 0;
    static volatile long sum = 0;

    public static void main(String[] args) throws Exception {
        System.out.println(" 服务器运行, 等待客户端连接");
        ServerSocket server = new ServerSocket(GradeClient.PORT);
        boolean flag = true;
        for (int i = 0; i < 10; i++) {
            Socket client = server.accept();
            GradeServer ts = new GradeServer("线程 " + i, client);
            ts.start();
        }
        countDownLatch.await();
        server.close();
    }

    @Override
    public void run() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));) {

            System.out.println("客户端:" + socket.getInetAddress() + "已连接到服务器");
            //读取客户端发送来的消息 ka

            String mess = null;
            StringBuilder sb = new StringBuilder();
            while ((mess = br.readLine()) != null) {
                sb.append(mess);
            }
            mess = sb.toString();
            if (mess.matches("\\d++")) {
                processNewGrade(Integer.parseInt(mess));
            }
            System.out.println(" \t" + this.getName() + " : " + mess + " \t");
            countDownLatch.countDown();
            countDownLatch.await();
            // 最后在返回:
            bw.write("count = " + this.count + " Aveage Grade : " + getAve() + "\n");
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public GradeServer(String s, Socket client) {
        super(s);
        this.socket = client;
    }


    synchronized void processNewGrade(int grade) {
        count++;
        sum += grade;
    }

    double getAve() {
        return (double) sum / (double) count;
    }
}
